package com.xywl.escort.view.order.subscription

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.adapter.DeliverySpecAdapter
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.*
import com.xywl.escort.utils.ToastUtil
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_delivery_dialog.*
import kotlinx.android.synthetic.main.view_delivery_dialog_footer.view.*
import kotlinx.android.synthetic.main.view_order_header.view.*
import timber.log.Timber
import java.util.*
import javax.inject.Inject

/**
 * 发货弹框
 */
@Route(path = "/xy/order/delivery/dialog")
class DeliveryDialogActivity : BaseActivity(), DeliveryDialogContract.View {
    private lateinit var mAdapter: DeliverySpecAdapter
    private lateinit var headerView: View
    private lateinit var footerView: View
    private val REQUEST_CODE_CHOOSE_ADDRESS = 25

    @Inject
    lateinit var mPresenter: DeliveryDialogContract.Presenter

    private val list = ArrayList<ProjectSpecResp.DataBean>()

    private var addrBean: AddrBean? = null

    @Autowired
    @JvmField
    var projectId = ""

    @Autowired
    @JvmField
    var holdNum = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_delivery_dialog)
        ARouter.getInstance().inject(this)

        initView()
        initData()
        addListener()
    }

    private fun initView() {
        val manager = LinearLayoutManager(this)
        manager.orientation = LinearLayoutManager.VERTICAL
        recycler_spec.layoutManager = manager

        mAdapter = DeliverySpecAdapter(R.layout.item_delivery_specification, list)
        headerView = layoutInflater.inflate(R.layout.view_order_header, recycler_spec.parent as ViewGroup, false)
        footerView = layoutInflater.inflate(R.layout.view_delivery_dialog_footer, recycler_spec.parent as ViewGroup, false)
        mAdapter.addHeaderView(headerView)
        mAdapter.addFooterView(footerView)
        recycler_spec.adapter = mAdapter
    }

    private fun initData() {
        mPresenter.takeView(this)
        mPresenter.loadSpec(projectId)
        mPresenter.loadAddress()
    }

    private fun addListener() {
        headerView.text_receipt_info.setOnClickListener {
            ARouter.getInstance().build("/xy/address/manage").withInt("type", 1).navigation(this, REQUEST_CODE_CHOOSE_ADDRESS)
        }
        btn_confirm.setOnClickListener {
            delivery()
        }
        image_close.setOnClickListener {
            finish()
        }
        footerView.pop_reduce.setOnClickListener {
            subNum()
        }
        footerView.pop_add.setOnClickListener {
            addNum()
        }
    }

    /**
     * 增加数量
     */
    private fun addNum() {
        val strNum = footerView.pop_num.text.toString()
        val num = Integer.parseInt(strNum)
        if (holdNum - num > 0) {
            val numAdd = Integer.parseInt(strNum) + 1
            footerView.pop_num.text = numAdd.toString()
        } else {
            ToastUtil.showTip(this, "已达到最大发货量")
        }
    }

    /**
     * 减小数量
     */
    private fun subNum() {
        val strNum = footerView.pop_num.text.toString()
        if (Integer.parseInt(strNum) > 1) {
            val numReduce = Integer.parseInt(strNum) - 1
            footerView.pop_num.text = numReduce.toString()
        } else {
            ToastUtil.showTip(this, "不能再减少了")
        }
    }

    private fun delivery() {
        val req = DeliveryApplyReq()
        val size = list.size
        val specificList = ArrayList<ProjectSpecResp.DataBean.ProjectStandSmallListBean>()
        for (specificResp in list) {
            val map = specificResp.map
            if (null != map) {
                val key = specificResp.id
                val specific = map[key]
                if (null != specific) {
                    Timber.tag("DeliveryDialogActivity").e("specific.id=" + specific.id + " ,specific.name=" + specific.name)
                    specificList.add(specific)
                } else {
                    Timber.tag("DeliveryDialogActivity").e("null")
                }
            } else {
                Timber.tag("DeliveryDialogActivity").e("空")
            }
        }
        val standSmallIds = StringBuilder()
        val standSmallNames = StringBuilder()
        if (specificList.size < size) {
            ToastUtil.showTip(this, "规格选择不完整")
            return
        } else {
            for (specific in specificList) {
                standSmallIds.append(specific.id)
                standSmallIds.append(",")
                standSmallNames.append(specific.name)
                standSmallNames.append(",")
            }
            req.standSmallIds = standSmallIds.toString()
            req.standSmallNames = standSmallNames.toString()
            // ToastUtil.showTip(this, standSmallIds.toString() + " ;;; " + standSmallNames.toString())
        }
        req.projectId = projectId
        val num = footerView.pop_num.text.toString().trim()
        if (!TextUtils.isEmpty(num)) {
            req.num = Integer.valueOf(num)
        }

        if (null != addrBean) {
            if (null != addrBean!!.id && null != addrBean!!.contactNumber && null != addrBean!!.city
                    && null != addrBean!!.district && null != addrBean!!.address && null != addrBean!!.contacts
                    && null != addrBean!!.province) {
                req.addressId = addrBean!!.id
                val addressDetail = addrBean!!.province + addrBean!!.city + addrBean!!.district + addrBean!!.address
                req.addressDetail = addressDetail
                req.contacts = addrBean!!.contacts
                req.contactNumber = addrBean!!.contactNumber
            } else {
                ToastUtil.showTip(this, "请选择地址")
                return
            }
        } else {
            ToastUtil.showTip(this, "请选择地址")
            return
        }
        val remark = footerView.edit_remark.text.toString().trim()
        req.remark = remark
        mPresenter.delivery(req)
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun loadSpecSuccess(data: MutableList<ProjectSpecResp.DataBean>?) {
        list.addAll(data!!)
        mAdapter.setNewData(list)
    }

    override fun loadSpecFailure() {
        Timber.e("loadSpecFailure")
    }

    override fun loadAddressSuccess(resp: DefaultResp?) {
        addrBean = resp!!.data
        setAddressInfo(addrBean)
    }

    override fun loadAddressFailure() {
        Timber.e("loadAddressFailure")
    }

    override fun deliverySuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "操作成功！！！")
        finish()
    }

    override fun deliveryFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    private fun setAddressInfo(bean: AddrBean?) {
        if (null != bean) {
            headerView.text_name.text = bean.contacts
            val contactNumber = bean.contactNumber
            headerView.text_phone.text = contactNumber
            val province = bean.province
            val city = bean.city
            val district = bean.district
            val address = bean.address
            if (TextUtils.isEmpty(province) || TextUtils.isEmpty(city)
                    || TextUtils.isEmpty(district) || TextUtils.isEmpty(address)) {
                headerView.text_empty_address.visibility = View.VISIBLE
                headerView.layout_address.visibility = View.GONE
            } else {
                headerView.text_empty_address.visibility = View.GONE
                headerView.layout_address.visibility = View.VISIBLE
                val detailAddress = province + city + district + address
                headerView.text_address.text = detailAddress
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_CHOOSE_ADDRESS -> {
                    data?.let {
                        addrBean = data.getSerializableExtra("address") as AddrBean
                        Timber.e("bean=${addrBean!!.address}")
                        setAddressInfo(addrBean)
                    }
                    Timber.e("data=$data")
                }
                else -> {
                }
            }
        }
    }
}
